// 官方文档：https://docs.microsoft.com/zh-cn/aspnet/core/signalr/javascript-client?view=aspnetcore-6.0&viewFallbackFrom=aspnetcore-2.2&tabs=visual-studio
import * as signalR from '@microsoft/signalr'
import store from '../store'
import configService from '@/api/config.service'
import {
  getToken
} from '@/utils/auth'

export default {
  // signalR对象
  SR: {},
  // 失败连接重试次数
  failNum: 4,
  baseUrl: '',
  init(url) {
    var socketUrl = configService.apiUrl + url + '?from=h5'
    const connection = new signalR.HubConnectionBuilder()
      .withUrl(socketUrl, {
        accessTokenFactory: () => getToken()
      })
      .withAutomaticReconnect() //自动重新连接
      .configureLogging(signalR.LogLevel.Warning)
      .build()
    this.SR = connection
    // 断线重连
    connection.onclose(async () => {
      console.log('断开连接了')
      console.assert(connection.state === signalR.HubConnectionState.Disconnected)
      await this.start()
    })

    connection.onreconnected(() => {
      console.log('断线重新连接成功')
    })

    connection.onreconnecting(async () => {
      console.log('断线重新连接中... ')
      await this.start()
    })

    this.receiveMsg(connection)
    // 启动
    // this.start();
  },
  /**
   * 调用 this.signalR.start().then(async () => { await this.SR.invoke("method")})
   * @returns
   */
  async start() {
    var that = this

    try {
      console.log('signalR-1', this.SR.state)
      //使用async和await 或 promise的then 和catch 处理来自服务端的异常
      if (this.SR.state === signalR.HubConnectionState.Disconnected) {
        await this.SR.start()
      }
      console.log('signalR-2', this.SR.state)
      return true
    } catch (error) {
      console.error(error)
      that.failNum--
      if (that.failNum > 0 && this.SR.state.Disconnected) {
        setTimeout(async () => {
          await this.SR.start()
        }, 5000)
      }
      return false
    }
  },
  // 接收消息处理
  receiveMsg(connection) {
    connection.on('onlineNum', (data) => {
      // store.dispatch('socket/changeOnlineNum', data)
    })
    connection.on('onlineInfo', (data) => {
      console.log(data)
    })
    // 接收欢迎语
    connection.on('moreNotice', (data) => {})
    connection.on('connId', (data) => {
      store.dispatch('saveConnId', data)
    })
    // 接收后台手动推送消息
    connection.on('receiveNotice', (title, data) => {
      uni.showModal({
        title: title,
        content: data,
        showCancel: false
      })
    })
    // 接收强退通知
    connection.on('forceUser', (data) => {
      uni.showModal({
        title: '提示',
        content: `你的账号已被强退，原因：${data.reason || '无'}`,
        showCancel: false,
        complete() {
          store.dispatch('LogOut').then(() => {
            // uni.reLaunch({
            //   url: '/pages/login'
            // })
            window.location.href = '/pages/login'
          })
        }
      })
    })

    // 接收聊天数据
    connection.on('receiveChat', (data) => {
      const title = `来自${data.userName}的消息通知`

      uni.showModal({
        title: title,
        content: data.message,
        showCancel: false
      })
    })
  },
}